package com.hmdp.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.hmdp.Interceptor.LoginInterceptor;
import com.hmdp.Interceptor.RefreshInterceptor;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RefreshInterceptor(stringRedisTemplate)).order(1);
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/shop/**",
                        "/voucher/**",
                        "/shop-type/**",
                        "/upload/**",
                        "/blog/hot",
                        "/user/code",
                        "/user/login"
                ).order(2);
    }

//    @Bean
//    public RedissonClient redissonClient() {
//        Config config = new Config();
//        config.useSingleServer().setAddress("redis://192.168.88.130:6379");
//        return Redisson.create(config);
//    }

    @Bean
    public Cache<String, Object> cache() {
        return Caffeine.newBuilder()
                .maximumSize(1000)          // 最大条目数
                .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
                .build();
    }

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        // 集群模式配置
        config.useClusterServers()
                .addNodeAddress(
                        "redis://192.168.88.130:7001",
                        "redis://192.168.88.130:7002",
                        "redis://192.168.88.130:7003"
                )
                .setScanInterval(2000) // 集群节点状态扫描间隔（毫秒）
                // .setPassword("566598") // 如果集群有密码
                .setCheckSlotsCoverage(false); // 关闭槽位完整检查（慎用）
        return Redisson.create(config);
    }
}
